package com.fcy.teamwork.business.newproject

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import cn.jpush.im.android.api.JMessageClient
import cn.jpush.im.android.api.callback.CreateGroupCallback
import cn.jpush.im.android.api.model.Conversation
import com.fcy.teamwork.App
import com.fcy.teamwork.pojo.ProjectInfo
import com.fcy.teamwork.pojo.TeamWorkResult
import com.fcy.teamwork.repo.RetrofitClient
import kotlinx.coroutines.launch
import retrofit2.http.Body
import retrofit2.http.POST
import java.time.Instant
import java.util.*
import kotlin.coroutines.resume
import kotlin.coroutines.suspendCoroutine

private interface NEWProjectService {
    @POST("/sms/project/newProject")
    suspend fun submitNewProject(@Body projectInfo: ProjectInfo): TeamWorkResult<Boolean>
}

class NewProjectActVM : ViewModel() {
    private val service: NEWProjectService by lazy { RetrofitClient.getService() }
    fun loadUIElement(): List<ProjectInfoAdapter.InfoItem> {
        return listOf(
            ProjectInfoAdapter.InfoItem("项目名称", 20),
            ProjectInfoAdapter.InfoItem("项目详细描述", 255),
            ProjectInfoAdapter.InfoItem("项目类型", 20),
            ProjectInfoAdapter.InfoItem("计划需要时间", 20)
        )
    }

    suspend fun submitInfo(info: List<ProjectInfoAdapter.InfoItem>): Boolean {
        if (!checkInfo(info)) {
            // 未填写完整
            return false
        }
        val projectInfo = processElement(info)
        val submitNewProject = service.submitNewProject(projectInfo)
        return submitNewProject.isOk
    }

    private suspend fun processElement(info: List<ProjectInfoAdapter.InfoItem>): ProjectInfo =
        suspendCoroutine {
            JMessageClient.createPublicGroup(info[0].content, "", object : CreateGroupCallback() {
                override fun gotResult(p0: Int, p1: String?, p2: Long) {
                    if (p0 == 0) {
                        val msg = Conversation.createGroupConversation(p2)
                            .createSendTextMessage("欢迎大家加入${info[0].content}项目")
                        JMessageClient.sendMessage(msg)
                        it.resume(
                            ProjectInfo(
                                p2.toInt(),
                                info[0].content,
                                App.person.personId,
                                Date.from(Instant.now()),
                                info[1].content,
                                info[2].content,
                                p2.toString(),
                                info[3].content
                            )
                        )
                    }
                }
            })
        }

    private fun checkInfo(info: List<ProjectInfoAdapter.InfoItem>): Boolean {
        return info.firstOrNull {
            it.content.isBlank()
        } == null
    }
}